import 'dart:async';

import 'package:dartlearn/src/template/message_template.dart';
import 'package:socket_io_client/socket_io_client.dart' as IO;
import 'package:socket_io_client/socket_io_client.dart';

main(List<String> args) {
  // 790883082764030000 陆游
  // 790883082730475500 苏轼
  // 775113183131074560 王昭君
  // 786600935907659776 桃花
  // 775113183131074580 江景

  String toUserId = '786600935907659776';
  String currentUserId = '775113183131074560';
  String accessToken = '4adcfb27-1783-41e9-8937-3ed4a73830cc';
  IO.Socket channel = IO.io(
      'http://localhost:9000?userId=$currentUserId&access_token=$accessToken',
      OptionBuilder()
          // for Flutter or Dart VM
          .setTransports(['websocket'])
          // disable auto-connection
          .disableAutoConnect()
          // optional
          .setExtraHeaders({'access_token': accessToken})
          .build());

  channel.connect();

  // 链接建立成功之后，可以发送数据到socket.io的后端了
  channel.on('connect', (data) => print('connect $data'));

  // 链接建立失败时调用
  channel.on('error', (data) => print('error $data'));

  // 链接出错时调用
  channel.on("connect_error", (data) => print('connect_error: $data'));

  // 链接断开时调用
  channel.on('disconnect', (data) => print('disconnect $data'));

  // 链接关闭时调用
  channel.on('close', (data) => print('close $data'));

  // 服务端 emit 一个 message 事件时，可以直接监听到
  channel.on('message', (data) => print('onmessage $data'));

  channel.on('SINGLE_CHAT', (data) => print('onmessage $data'));

  Timer.periodic(Duration(seconds: 3), (timer) {
    MessageTemplate template = MessageTemplate(
        type: "MS:TEXT",
        chatType: "CT:SINGLE",        
        sendId: currentUserId,
        receiveId: toUserId,
        content: "你好，我是王昭君！");
    channel.emit('SINGLE_CHAT', template.toJson());
  });
}
